#!/bin/bash
# ZIP还原脚本 - 还原到指定目录，执行完整性校验

# 配置区 ========================================
ARCHIVE_DIR="/var/openebs/local/pvc-847c635d-6782-495e-95f9-88d088a73716/pigeonhole/bak"
RESTORE_DIR="/var/openebs/local/pvc-847c635d-6782-495e-95f9-88d088a73716/f92b609c-84f5-4094-b3ff-d554f8b54734-bak/"  # 还原目录
# ==============================================

set -euo pipefail

echo "可用的ZIP归档包："
ls "$ARCHIVE_DIR"/*_archive.zip 2>/dev/null | nl -w2 -s'. '

if [ $? -ne 0 ]; then
    echo "没有发现任何归档文件！"
    exit 1
fi

read -p "请输入要还原的编号: " NUM

ARCHIVES=("$ARCHIVE_DIR"/*_archive.zip)
if [ "$NUM" -le 0 ] || [ "$NUM" -gt "${#ARCHIVES[@]}" ]; then
    echo "无效编号" >&2
    exit 1
fi
SELECTED_ARCHIVE=${ARCHIVES[$((NUM-1))]}
MONTH=$(basename "$SELECTED_ARCHIVE" | cut -d'_' -f1)
CHECKSUM_FILE="${ARCHIVE_DIR}/${MONTH}_checksums.sha256"

echo "正在验证ZIP包完整性..."
if ! unzip -tq "$SELECTED_ARCHIVE"; then
    echo "ZIP包损坏或无法解压！" >&2
    exit 1
fi
echo "ZIP包验证通过。"

mkdir -p "$RESTORE_DIR"
echo "正在还原到: $RESTORE_DIR"
unzip -q "$SELECTED_ARCHIVE" -d "$RESTORE_DIR"

echo "正在校验还原文件完整性..."
(cd "$RESTORE_DIR" && sha256sum -c "$CHECKSUM_FILE" 2>/dev/null | grep -vF "_archive.zip") || {
    echo "某些文件校验失败，请检查！"
    exit 1
}

echo -e "\n还原完成！"
echo "文件原始路径结构已还原至: $RESTORE_DIR"
echo "如需恢复到原始位置，请确保数据安全后，手动执行类似命令："
echo "sudo unzip -q $SELECTED_ARCHIVE -d /"
